/**
 * Created by hjqi on 2016/3/2.
 */

var express = require('express');
var router = express.Router();
var config = require('../lib/config/config').config;
var httpRequest = require('../lib/common/httpRequest').httpRequest;
var _req = new httpRequest();
var qs = require('querystring');

router.post('/publishImg', function (req, res, next) {
    var param = req.body;
    var  _registerUrl = config.register.host+':'+config.register.port;
    var _imgName = _registerUrl + '/'+req.username+'/'+param.id+':'+param.tag;

    var _envns = global.ENVIRONMENT.QA;
    var role = req.cookies.role;
    if (role == global.ROLE.DEVELOPER) {
        _envns = global.ENVIRONMENT.QA;
    } else if (role == global.ROLE.QAER) {
        _envns = global.ENVIRONMENT.PROD;
        _imgName = _registerUrl + '/' + global.ENVIRONMENT.QA + '/' + param.id + ':' + param.tag;
    }

    var _tagAndpush = new Promise(function (resolve, reject){

        var _repoName = _registerUrl + '/' + _envns + '/' + param.id;
        var _repoNameWithTag =  _repoName +':'+param.tag;
        var _url = 'http://' + config.docker.host + ':' + config.docker.port + '/images/' + _imgName + '/tag?';
        var _urlParam = {
            "repo":_repoName,
            "tag":param.tag,
            "force":1
        };
        _url += qs.stringify(_urlParam);

        _req._request(_url, 'POST',{} , '' , function (data, result, response) {
            if (data !== null && data.statusCode == 201 )
                resolve(_repoName);
            else
                reject(result);
        });
    });

    _tagAndpush.then(function(reponame){
        var _url = 'http://' + config.docker.host + ':' + config.docker.port + '/images/' + reponame + '/push?';
        var _urlParam = {
            "tag":param.tag
        };
        _url += qs.stringify(_urlParam);
        _req._request(_url, 'POST', {"X-Registry-Auth":"test"}, '' , function (data, result, response) {
            if (data !== null){
                var _retlst = data.data.split('\n');
                var _last = _retlst[_retlst.length - 1];
                if(_last === '')
                    _last = _retlst[_retlst.length - 2];
                var _obj = JSON.parse(_last);
                if(_obj.status.indexOf("Pushing tag for rev") != -1)
                    res.send(true);
                else
                    res.send(false);
            }
            else
                res.send(false);
        });

    }).catch(function(resp){
        res.send(resp);
    });






});

module.exports = router;